<?php

class Client_Table_Products extends Apk_Db_Table
{
	protected $_name      = 'products';
    protected $_primary   = 'id';
    protected $_ERROR = '';
    protected $_lang;

    public function __construct($lang = 'ru')
    {
    	$this->_lang = $lang;
    	parent::__construct();
    }

    public function GetError()
    {
    	return $this->_ERROR;
    }

    public function GetDataList($page=1, $params=array())
    {
    	$perPageCount = 200;
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'idt', 'id_cat', 'path', 'file_name', 'art', 'title' => 'title_'.$this->_lang, 'desc' => 'desc_'.$this->_lang, 'body' => 'body_'.$this->_lang, 'info' => 'info_'.$this->_lang, 'subtitle' => 'subtitle_'.$this->_lang, 'is_show_gallery'))
    		  ->join('categories', 'categories.id = products.id_cat', array('url'))
    		  ->where($this->_name.'.is_active = 1')
    		  ->where($this->_name.'.is_ghost = 0')
    		  ->where($this->_name.'.is_removed = 0')
    		  ->order($this->_name.'.title_'.$this->_lang);

    	// **  Params  **
    	if(count($params) > 0)
    	foreach ($params as $k => $v)
    	switch($k)
    	{
    		case 'cats':
    			$sel->where('id_cat in (?)', $v);
    			break;
			case 's':
					if(trim($v) != '')
					{
						$sel->where($this->_name.'.title_'.$this->_lang.' like \'%'.$v.'%\' or '.$this->_name.'.desc_'.$this->_lang.' like \'%'.$v.'%\'   ');
						//$sel->group($this->_name.'.id');
						//$perPageCount = 500;
					}
					break;
    		default:
    			$sel->where($this->_name.'.'.$k.' = ?', $v);
    	}

    	//echo $sel; die();

    	try{
    		return $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $perPageCount));
    	}catch(Exception $e)
    	{
    		echo $e->__toString(); die();
    	}
    }

    public function GetLast($limit = 3)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name, array('id', 'idt', 'id_cat', 'path', 'file_name', 'art', 'title' => 'title_'.$this->_lang, 'desc' => 'desc_'.$this->_lang, 'body' => 'body_'.$this->_lang, 'info' => 'info_'.$this->_lang, 'subtitle' => 'subtitle_'.$this->_lang, 'is_show_gallery'))
    				->where('is_active')
    				->where('is_removed = 0')
    				->where('is_ghost = 0')
    				->order('public_date desc')
    				->limit($limit);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }


    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name, array('id', 'idt', 'id_cat', 'path', 'file_name', 'art', 'title' => 'title_'.$this->_lang, 'desc' => 'desc_'.$this->_lang, 'desc_full' => 'desc_full_'.$this->_lang, 'body' => 'body_'.$this->_lang, 'info' => 'info_'.$this->_lang, 'dop_options' => 'dop_options_'.$this->_lang, 'subtitle' => 'subtitle_'.$this->_lang, 'is_show_gallery'))
		    		->where($this->_name.'.is_active')
		    		->where($this->_name.'.is_removed = 0')
		    		->where($this->_name.'.is_ghost = 0');


    	if(intval($id) > 0) $sel->where($this->_name.'.id = ?', $id);
		else $sel->where($this->_name.'.idt = ?', $id);

		//echo $sel; die();

		try {
	    	$data = $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();
		}
		catch (Exception $e)
		{
			return array();
		}

    	//$data['tags'] = $this->GetTags($data['id']);
    	//$data['arts'] = $this->GetArts($data['id']);
    	//$data['childs'] = $this->GetChilds($data['id']);
    	$data['files'] = $this->GetFiles($data['id']);

    	return $data;
    }


    public function GetArts($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from('products_arts')
    				->where('id_prod = ?', $id)
    				->where('is_active')
    				->where('is_removed = 0')
    				->where('is_ghost = 0')
    				->order('norder');

    	$data =  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();

    	if(isset($data[0]['id']))
    	foreach($data as $k => $v)
    	{
			$data[$k]['vals'] = $this->GetArtsVals($v['id']);
    	}

    	return $data;
    }

	public function GetArtsVals($id)
	{
        $sel = $this->getAdapter()->select()
    				->from('products_arts_val')
    				->where('id_art = ?', $id);
    	return  $this->getList($sel)->toArray();
	}

    public function GetChilds($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from('products_rel')
    				->join('products', 'products.id = products_rel.id_child')
    				->join('categories', 'categories.id = products.id_cat', array('url'))
    				->where('products_rel.id_parent = ?', $id)
    				->where('products.is_active')
    				->where('products.is_removed = 0')
    				->where('products.is_ghost = 0')
    				->order('products.norder');

    	return  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();

    }

    public function GetTags($id)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('tags_to_products')
    		  ->join('tags', 'tags.id = tags_to_products.id_tag', array('id', 'name', 'unit'))
    		  ->where('tags.is_active')
    		  ->where('tags_to_products.id_products = ?', $id)
    		  ->order('tags_to_products.norder');

    	return $this->getList($sel)->toArray();
    }

    public function GetComments($id)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('articles_comments')
    		  ->join('accounts', 'accounts.id = articles_comments.id_acc', array('username', 'path', 'file_name'))
    		  ->where('articles_comments.id_article = ?', $id);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function GetFiles($id)
    {
       	$sel = $this->getAdapter()->select()
    				->from('pdf', array('id', 'id_cat', 'id_prod', 'path', 'file_name', 'file_name_var', 'title' => 'title_'.$this->_lang, 'desc' => 'desc_'.$this->_lang, 'file_size'))
    				->where('is_active')
    				->where('is_removed = 0')
    				->where('is_ghost = 0')
    				->where('id_prod = ?', $id)
    				->order('norder');


    	return  $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function AddHit($id)
    {
    	$data = $this->GetDataRow($id);

    	$d['hit_count'] = $data['hit_count'] + 1;
    	$this->update($d, 'id = '.$id);

    	return true;
    }

    public function is_rated($id, $ip_addr)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('articles_rating')
    		  ->where('ip_addr = ?', $ip_addr)
    		  ->where('id_article = ?', $id);

    	return $this->getList($sel)->count();
    }

    public function rating($data)
    {
    	if($this->is_rated($data['id_article'], $data['ip_addr'])) return false;

    	$data['date'] = time();

    	$this->getAdapter()->insert('articles_rating', $data);
    	$this->calc_rate($data['id_article']);
    	return true;
    }

    public function calc_rate($id)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('articles_rating', array('count' => 'count(id)', 'sum' => 'sum(value)'))
    		  ->where('id_article = ?', $id);

    	$data = $this->getList($sel)->getRow(0);

    	$d['rating_count'] = $data->count;
    	if($data->count > 0) $d['rating'] = $data->sum / $data->count;
    	else $d['rating'] = 0;

    	parent::update($d, 'id = '.$id);
    }

    public function comment($data)
    {
    	$data['add_date'] = time();
    	$this->getAdapter()->insert('articles_comments', $data);
    	return $this->getAdapter()->lastInsertId('articles_comments');
    }

    public function GetAccessList($a = null, $lang = 'ru')
    {
    	$ret = array();

		$sel = $this->getAdapter()->select()
					->from('access_level', array('id', 'title' => 'title_'.$lang))
					->order('title_ru');

		$data = $this->getList($sel)->toArray();

    	if(count($data) > 0 && !is_null($a))
    	foreach($data as $k => $v)
    	  	if($v['id'] == $a) $data[$k]['__attributes']['active'] = 1;

    	return $data;
    }




    //**********************************************
    // insert/update/delete

	public function insert(array $data, $user_id)
    {
    	$data['public_date'] = time();
    	$data['modify_date'] = time();
    	$data['add_date'] = time();
    	$data['add_user_id'] = $user_id;
    	$data['modify_user_id'] = $user_id;
    	$data['is_ghost'] = 0;
    	$data['is_active'] = 1;

        return parent::insert($data);
    }

    public function update(array $data, $id, $user_id = 0)
    {
    	$data['modify_date'] = time();
    	$data['modify_user_id'] = $user_id;
    	$data['is_ghost'] = 0;

    	//if(!isset($data['is_active'])) $data['is_active'] = 0;
    	//if(!isset($data['is_commented'])) $data['is_commented'] = 0;
    	//if(!isset($data['is_rated'])) $data['is_rated'] = 0;

		return parent::update($data, 'id = '.$id);
    }

    public function remove($items, $user_id)
    {
    	foreach($items as $k => $id)
    	{
	    	$data['modify_user_id'] = $user_id;
	    	$data['modify_date'] = time();
	    	$data['is_removed'] = 1;

	    	parent::update($data, 'id = '.$id);
    	}

    	return true;
	}

    public function remove_commetns($items, $aid)
    {
    	foreach($items as $k => $id)
    	{
	    	$this->getAdapter()->delete('articles_comments', 'id = '.$id);
    	}

    	$this->commetns_count($aid);

    	return true;
	}

    public function commetns_count($id)
    {
    	$sel = $this->getAdapter()->select()
    					->from('articles_comments', array('count' => 'count(id)'))
    					->where('id_article = ?', $id);
    	$count = $this->getList($sel)->getRow(0)->toArray();

    	$d['comments_count'] = $count['count'];
    	parent::update($d, 'id = '.$id);
    }


    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            case 'unit':
				switch($value)
				{
				   case 'm2':
				   case 'м2':
				   		$result[$key] = 'm<sup>2</sup>';
				   		break;
				   case 'm3':
				   case 'м3':
				   		$result[$key] = 'm<sup>3</sup>';
				   		break;
				   case 'mm3':
				   		$result[$key] = 'mm<sup>3</sup>';
				   		break;
				   	case 'mm2':
				   		$result[$key] = 'mm<sup>2</sup>';
				   		break;
				   	default:
				   		$result[$key] = stripslashes($value);
				}
            	break;
             case 'file_size':
                $result[$key] = round($value/1024/1024, 2).' MB';
                break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

    public function topDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;

            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>